﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

[RequireComponent(typeof(ToggleGroup))]
public class ListTogglesGroup : MonoBehaviour {

    ToggleGroup m_Group;
    public ToggleGroup group => m_Group;
    public List<ListToggleItem> toggleItems = new List<ListToggleItem>();
    Action<int> onSelect;

    int m_SelectIndex;

    private void Awake()
    {
        m_Group = GetComponent<ToggleGroup>();
    }

    void Start()
    {

    }

    public void Init(Action<int> _onSelect, int defaultValue)
    {
        m_SelectIndex = defaultValue;
        Init(_onSelect,null, defaultValue);
    }

    public void Init(Action<int> _onSelect,List<int> valuesList,int defaultValue)
    {
        if(m_Group == null)
            m_Group = GetComponent<ToggleGroup>();

        onSelect = _onSelect;

        if (valuesList != null)
        {
            for (int i = 0; i < toggleItems.Count; i++)
            {
                if (i < valuesList.Count)
                {
                    toggleItems[i].Init(m_Group, valuesList[i], OnSelect);
                }
                else
                {
                    toggleItems[i].Init(m_Group,i, OnSelect);
                }
            }
        }
        else
        {
            for (int i = 0; i < toggleItems.Count; i++)
            {
                toggleItems[i].Init(m_Group,OnSelect);
            }
        }
        
        foreach (var togItem in toggleItems)
        {
            togItem.isOn = false;
        }
        var tog = toggleItems.Find(e => e.id == defaultValue);
        if (tog)
        {
            tog.isOn = true;
            OnSelect(defaultValue);
        }
    }
    

    void OnSelect(int id)
    {
        if (onSelect != null)
            onSelect(id);
    }


}
